/* bkerndev - Bran's Kernel Development Tutorial
 * By:   Brandon F. (friesenb@gmail.com)
 * Desc: Keyboard driver
 *
 * Notes: No warranty expressed or implied. Use at own risk.
 */

#include <sys/io.h>

#include "fixedQueue.h"

#include "keyboard_layouts.h"

extern keyboard_layout kbdus;

fixedQueue keyboard_queue;


/* Handles the keyboard interrupt */
static void keyboard_handler(void)
{
	unsigned char* kbd = kbdus[KB_NORMAL];

	/* Read from the keyboard's data buffer */
    unsigned char scancode = inb(0x60);

    /* If the top bit of the byte we read from the keyboard is set,
     * that means that a key has just been released */
    if(scancode & 0x80)
    {
        scancode -= 0x80;   // Get key from scancode

//    	printf("[release] %s: %i, %c\n", "scancode", scancode, kbd[scancode]);
//    	eventmanager_send("keyboard/release/scancode",scancode);
    }
    else
    {
        /* Here, a key was just pressed. Please note that if you hold a key
         * down, you will get repeated key press interrupts. */

    	fixedQueue_append(&keyboard_queue, &kbd[scancode]);
//    	printf("[press  ] %s: %i, %c\n", "scancode", scancode, kbd[scancode]);
//    	eventmanager_send("keyboard/press/scancode",scancode);
    }
}

/* Installs the keyboard handler into IRQ1 */
void keyboard_init(void)
{
	static char keyboard_queue_items[10];

	fixedQueue_init(&keyboard_queue, keyboard_queue_items, sizeof(char));
	keyboard_queue.capacity = 10;	// Hugly hack

	irq_handler_register(33, &keyboard_handler);
}
